package com.ballyza.gals;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import com.ballyza.SemanticAction;

public class Semantico implements Constants {

	private SemanticAction actions;

	public Semantico(String nomeArquivo) {
		actions = new SemanticAction(nomeArquivo);
	}

	public void executeAction(int action, Token token) throws SemanticError {
		// System.out.println("Ação #" + action + ", Token: " + token);

		Method method = getExecuteActionMethod(action);
		try {
			method.invoke(actions, token);
		} catch (SemanticError error) {
			throw error;
		} catch (Exception e) {
			if (e instanceof InvocationTargetException) {
				InvocationTargetException ie = (InvocationTargetException) e;
				if (ie.getTargetException() instanceof SemanticError) {
					SemanticError error = (SemanticError) ie
							.getTargetException();
					throw error;
				}
			}
			e.printStackTrace();
		}
	}

	private Method getExecuteActionMethod(int action) {
		String strAction = String.valueOf(action);
		final String methodName = "executeAction".concat(strAction);
		Method metodo = null;
		try {
			metodo = SemanticAction.class.getDeclaredMethod(methodName,
					Token.class);
		} catch (Exception e) {
			return null;
		}

		return metodo;
	}

	public SemanticAction getActions() {
		return actions;
	}

	public void setActions(SemanticAction actions) {
		this.actions = actions;
	}

}
